package com.example.chatroom.service.impl;

import com.example.chatroom.common.errorcode.ServiceErrorCodeConstants;
import com.example.chatroom.common.exception.ServiceException;
import com.example.chatroom.common.utils.JWTUtil;
import com.example.chatroom.controller.result.FriendListResult;
import com.example.chatroom.dao.dataobject.FriendInfoDO;
import com.example.chatroom.dao.dataobject.MessageSessionDO;
import com.example.chatroom.dao.dataobject.MessageSessionUserDO;
import com.example.chatroom.dao.mapper.FriendMapper;
import com.example.chatroom.dao.mapper.MessageMapper;
import com.example.chatroom.dao.mapper.MessageSessionMapper;
import com.example.chatroom.dao.mapper.MessageSessionUserMapper;
import com.example.chatroom.service.ISessionService;
import com.example.chatroom.service.dto.SessionListDTO;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SessionServiceImpl implements ISessionService {
    @Autowired
    private JWTUtil jwtUtil;
    @Autowired
    private MessageSessionUserMapper messageSessionUserMapper;
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    /**
     * 获取会话列表
     * @param request
     * @return
     */
    @Override
    public List<SessionListDTO> getSessionList(HttpServletRequest request) {
        //1-    判断user_token是否存在
        String userToken=request.getHeader("user_token");
        if(!StringUtils.hasLength(userToken)){
            log.info(ServiceErrorCodeConstants.USER_TOKEN_NOT_EXISTS.getMsg());
            throw new ServiceException(ServiceErrorCodeConstants.USER_TOKEN_NOT_EXISTS);
        }
        //2-    校验令牌是否合法
        Claims verify = jwtUtil.verify(userToken);
        if(verify==null){
            log.error("Token非法 user_token:{}",userToken);
            throw new ServiceException(ServiceErrorCodeConstants.USER_TOKEN_UNLAWFUL);
        }
        //3-    通过登陆用户id获取会话列表
        Long userId= jwtUtil.getUserId(userToken);
        //获取当前用户相关的会话
        List<Long>sessionIds=messageSessionUserMapper.selectByUserId(userId);

        return sessionIds.stream().map(sessionId->{
            SessionListDTO sessionListDTO=new SessionListDTO();
            sessionListDTO.setId(sessionId);
            //根据会话查询有关用户
            List<FriendInfoDO> friendInfoDOS=messageSessionUserMapper.selectBySessionId(sessionId,userId);
            if(friendInfoDOS.isEmpty()){
                sessionListDTO.setFriends(new ArrayList<>());
            }
            sessionListDTO.setFriends(friendInfoDOS.stream().map(friendInfoDO -> {
                FriendListResult friendListResult=new FriendListResult();
                friendListResult.setFriendId(friendInfoDO.getFriendId());
                friendListResult.setFriendName(friendInfoDO.getFriendName());
                return friendListResult;
            }).collect(Collectors.toList()));
            sessionListDTO.setLastMessage(messageMapper.selectBySessionId(sessionId)==null?" ":messageMapper.selectBySessionId(sessionId));
            return sessionListDTO;
        }).collect(Collectors.toList());
    }

    @Transactional
    @Override
    public Long addSession(Long toUserId,String userToken) {
        if(toUserId==null||toUserId<0){
            log.info(ServiceErrorCodeConstants.SESSION_PARAM_ERROR.getMsg());
            throw new ServiceException(ServiceErrorCodeConstants.SESSION_PARAM_ERROR);
        }
        //1-    获取当前登陆用户Id
        Long userId= jwtUtil.getUserId(userToken);
        //2-    根据用户Id获取会话Id
        List<Long>sessionIds=messageSessionUserMapper.selectByUserId(userId);
        //3-    判断会话Id与toUserId是否在session-user表中
        Long tmp=messageSessionUserMapper.selectBySUId(sessionIds,toUserId);
        if(tmp==0){
            //不存在，创建一个session
            MessageSessionDO messageSessionDO=new MessageSessionDO();
            messageSessionDO.setGmtCreate(new Date());
            messageSessionDO.setGmtModified(new Date());
            messageSessionMapper.insertSelective(messageSessionDO);
            //获取sessionId，再将sessionId、toUserId添加到sessionUser表
            MessageSessionUserDO messageSessionUserDO=new MessageSessionUserDO();
            messageSessionUserDO.setSessionId(messageSessionDO.getId());
            messageSessionUserDO.setUserId(toUserId);
            messageSessionUserMapper.insertSelective(messageSessionUserDO);
            //当前用户也需要加入到这个sessionUser表中
            MessageSessionUserDO messageSessionUserDO1=new MessageSessionUserDO();
            messageSessionUserDO1.setSessionId(messageSessionDO.getId());
            messageSessionUserDO1.setUserId(userId);
            messageSessionUserMapper.insertSelective(messageSessionUserDO1);
            return messageSessionDO.getId();
        }
        //不存在直接return
        return null;
    }
}
